import { type FC } from 'react';
import { RootSiblingPortal } from 'react-native-root-siblings';
import { useSafeState, useMemoizedFn, useUpdateEffect } from 'ahooks';
import DialogContent from './content';
import type { DialogProps } from './types';
export * from './function';

const Dialog: FC<DialogProps> = (props) => {
  const { open, destroyOnClose } = props;
  const [show, setShow] = useSafeState(open);
  const [created, setCreated] = useSafeState(open);

  const afterClose = useMemoizedFn(() => {
    props.afterClose?.();
    if (destroyOnClose) {
      setCreated(false);
    }
  });

  const showDialog = useMemoizedFn(() => {
    if (!created) setCreated(true);
    setTimeout(() => setShow(true), 10);
  });

  const closeDialog = useMemoizedFn(() => {
    setShow(false);
  });

  const updateState = useMemoizedFn(() => {
    open ? showDialog() : closeDialog();
  });

  useUpdateEffect(updateState, [open]);

  return created ? (
    <RootSiblingPortal>
      <DialogContent
        {...props}
        open={show}
        afterClose={afterClose}
      />
    </RootSiblingPortal>
  ) : null;
}

export default Dialog;